import type { Layer, Psd } from 'ag-psd'
import { readPsd } from 'ag-psd'

export interface PsdParseResult {
  psd: Psd
  layers: Layer[]
}
/**
 * 解析psd文件
 * @param file
 * @param onProcess
 */

export async function parsePsdFile(file: File, onProcess: Function): Promise<PsdParseResult> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = () => {
      const arrayBuffer = reader.result
      try {
        // @ts-ignore
        const psd = readPsd(arrayBuffer)
        onProcess()
        // 更新图层列表
        const layers = psd.children
        resolve({ psd, layers })
      }
      catch (e) {
        console.error(e)
        // @ts-ignore
        if (e.message.includes('Color mode not supported: CMYK')) {
          reject({ message: '暂不支持CMYK色彩模式的文件，请先使用PS转换为RGB' })
        }
        else {
          // @ts-ignore
          reject({ message: e.message })
        }
      }
    }
    reader.readAsArrayBuffer(file)
  })
}
